﻿using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[RoutePrefix("ProfileInvoice")]
	public class ProfileInvoiceController : BaseDbController
	{
		public ActionResult Index()
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			return View();
		}

		public async Task<JsonCamelCaseResult> GetData(int? page, int? rows, string sort, string order, ProfileConferenceAttendPayModel model)
		{
			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var sql = from conferenceAttendenceInfo in DbContext.ConferenceAttendenceInfo.AsNoTracking()
					.Where(x => x.Creator == LoginUser.UserName)
				  join conferenceMaster in DbContext.ConferenceMaster.AsNoTracking()
				      on conferenceAttendenceInfo.ConferenceId equals conferenceMaster.ID
				  join inv in DbContext.ConferenceInvoiceMaster.AsNoTracking()
				      on conferenceAttendenceInfo.InvoiceId equals inv.ID
				  select new
				  {
					  Id = conferenceAttendenceInfo.ID,
					  ConferenceName = conferenceMaster.ConferenceName,
					  FullName = conferenceAttendenceInfo.FullName,
					  InvoiceTitle = conferenceAttendenceInfo.InvoiceId,
					  TaxNum = conferenceAttendenceInfo.TaxNum,
					  AddressAndTel = conferenceAttendenceInfo.AddressAndTel,
					  Bank = conferenceAttendenceInfo.Bank,
					  BankAccount = conferenceAttendenceInfo.BankAccount,
					  InvoiceId = inv.InvoiceDetail,
					  Sort = conferenceMaster.Sort,
					  conferenceId = conferenceMaster.ID,
					  ConferenceNickName = conferenceMaster.ConferenceNickName,
					  HomePageUrl = conferenceMaster.HomePageUrl,
					  CreateDate = conferenceAttendenceInfo.CreateDate
				  };

			int total = await sql.CountAsync();

			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderByDescending(x => x.CreateDate).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();

			return JsonCamelCase(new
			{
				Total = total,
				Rows = sqlResult,
			},
			JsonRequestBehavior.AllowGet);
		}

		[Route("GetInvoiceInfoData/{id}")]
		public async Task<JsonCamelCaseResult> GetInvoiceInfoData(string id)
		{
			var invoice = await DbContext.ConferenceAttendenceInfo.AsNoTracking().FirstOrDefaultAsync(x => x.ID == id);

			if (invoice != null)
			{
				var result = new
				{
					id = invoice.ID,
					invoiceTitle = invoice.InvoiceTitle,
					taxNum = invoice.TaxNum,
					addressAndTel = invoice.AddressAndTel,
					bank = invoice.Bank,
					bankAccount = invoice.BankAccount,
					invoiceId = invoice.InvoiceId
				};
				return JsonCamelCase(Utility.CreateSuccessJsonResult(string.Empty, result),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> Modify(ProfileInvoiceModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			var info = await DbContext.ConferenceAttendenceInfo.FirstOrDefaultAsync(x => x.ID == model.cid);
			if (info != null)
			{
				using (var transaction = DbContext.Database.BeginTransaction())
				{
					info.InvoiceId = model.invoiceId;
					info.InvoiceTitle = model.invoiceTitle;
					info.TaxNum = model.taxNum;
					info.AddressAndTel = model.addressAndTel;
					info.Bank = model.bank;
					info.BankAccount = model.bankAccount;
					info.Updater = LoginUser.UserName;
					info.UpdateIP = LoginUser.IP;
					info.UpdateDate = DateTime.Now;

					await DbContext.SaveChangesAsync();
					transaction.Commit();
				}
				return JsonCamelCase(Utility.CreateSuccessJsonResult(),
						JsonRequestBehavior.AllowGet);
			}
			else
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgRecordNotExist),
						JsonRequestBehavior.AllowGet);
			}
		}
	}
}